package it.storm.solution;

/**
 * 1184. 公交站间的距离
 * https://leetcode-cn.com/problems/distance-between-bus-stops/
 */
public class Solutions_1184 {
    public static void main(String[] args) {
//        int[] distance = {1, 2, 3, 4};
//        int start = 0, destination = 1;  // output: 1

//        int[] distance = {1, 2, 3, 4};
//        int start = 0, destination = 2;  // output: 3

        int[] distance = {1, 2, 3, 4};
        int start = 0, destination = 3;  // output: 4

        int result = distanceBetweenBusStops(distance, start, destination);
        System.out.println(result);
    }

    public static int distanceBetweenBusStops(int[] distance,
                                              int start, int destination) {
        int n = distance.length;
        // [起点，终点)，不包含终点
        int left = Math.min(start, destination);
        int right = Math.max(start, destination);

        // 总距离
        int distantSum = 0;
        // 顺时钟走的距离
        int curDistant = 0;

        // 计算总距离的同时，也计算顺时钟从起点到终点的距离
        for (int i = 0; i < n; i++) {
            distantSum += distance[i];
            if (i >= left && i < right) {
                curDistant += distance[i];
            }
        }
        // 逆时钟方向距离 = 距离总和 - 顺时钟方向距离
        // Math.min(走顺时钟方向，走逆时钟方向)
        return Math.min(curDistant, distantSum - curDistant);
    }
}
